import wepy from 'wepy';
import util from './util';
import md5 from './md5';
import tip from './tip';
// import { USER_SPECICAL_INFO,API_CALLS,ConsoleLog } from '@/utils/constant';
import api from './api';
const APPID = 'slzrweapp'
const APPTYPE = 'WEAPP'
const APPKEY = 'A0E6C376000F44AEF13F58614C379DD9'


const wxRequest = async (params = {}, url, interval = 3) => {
    let data = params.data || {};
    let nonce = util.getNonce(10);
    let timeStamp = util.getTimeStamp();

  //检测是否调用过于频繁
  let apiCalls = wepy.getStorageSync(API_CALLS) || {};
  let lastTimeStamp = apiCalls[url] || 0;
  if(lastTimeStamp){
      if(timeStamp - lastTimeStamp < interval ) {
          console.log('调用接口['+ url +']频率过快，至少间隔'+ interval +'秒');
          return false;
      }
  }

  apiCalls[url] = timeStamp;
  wepy.setStorageSync(API_CALLS, apiCalls);

    var signStr = "AppId=" + APPID + "&AppKey=" + APPKEY + "&AppType=" + APPTYPE + "&Data=" + encodeURIComponent(JSON.stringify(data)) + "&Nonce=" + nonce + "&TimeStamp=" + timeStamp + "&Url=" + url;

    var sign = md5.hex_md5(signStr).toLocaleUpperCase();

 
    // wx.setStorageSync('SignSync', sign);
  
    let userSpeicalInfo = wepy.getStorageSync("USERLOGIN");
    let token = userSpeicalInfo == null ? '' : userSpeicalInfo.Token;

    let isUploadFile = data.FilePath != undefined;
    var CertNo = data.CertNo
    var VerifyPhotoUrl = data.VerifyPhotoUrl
    var CosFileKey = data.CompanyCodefile+'-'+data.uidfile+'-'+data.typefile

    var postData = {
        "AppType": APPTYPE,
        "AppId": APPID,
        "Nonce": nonce,
        "TimeStamp": timeStamp,
        "Signature": sign,
        "Data": data,
        "Url": url,
        "SignType": "MD5",
        "SignVersion": "1.1"
    };

    var header = {
        'Content-Type': isUploadFile ? 'multipart/form-data' : 'application/json',
        'Authorization': 'bearer ' + token
    };

    var requestData = JSON.stringify(postData);

    var tmpData = data;
    var imgUrls = [];
    var uploadImages = function (data) {
        var i = data.i ? data.i : 0,
            success = data.success ? data.success : 0,
            fail = data.fail ? data.fail : 0;

        +wx.uploadFile({
            url: url,
            header: header,
            filePath: data.FilePath[i],
            name: 'files',
            formData: { RequestData: requestData, FileType: CertNo?500:502,CosFileKey:CosFileKey+'-'+i },//502 ,CosFileKey:CosFileKey
            success: resp => {
                success++;
                console.log('++++++++++s',resp)

                var result = JSON.parse(resp.data);

                if (result.Code == 0)
                console.log('VerifyPhotoUrl--result.Data',result.Data)

                    imgUrls.push(result.Data.replace(/\\/g, '/'));
            },
            fail: res => {
                fail++;
                console.log('错误',res)
            },
            complete: (res) => {
                console.log('错误2',postData)

                i++;
                if (i == data.FilePath.length) {
                    let imgCertPhoto = []
                    let imgUserPhoto = []
                    let imgfirmrPhoto = []
                 if(VerifyPhotoUrl==''){
                    if(imgUrls.length==1){
                        imgfirmrPhoto.push(imgUrls[0])
                        tmpData['VerifyPhotoUrl'] = imgfirmrPhoto.join(',') + ',';
                        // tmpData['VerifyPhotoUrl'] = imgfirmrPhoto.join(',') + ',';
                    }
                console.log('VerifyPhotoUrl--imgUrls',imgUrls)

                 } else{

                if(imgUrls.length>2){
                
                     if(postData.Data.leix){
                         // 特种卡申请
                        console.log('VerifyPhotoUrl--tmpData特种卡申请',postData.Data)
                        imgCertPhoto.push(imgUrls[0],imgUrls[1])
                        imgUserPhoto.push(imgUrls[2],imgUrls[3])
                        tmpData['CertPhoto'] = imgCertPhoto.join(',');
                        tmpData['UserPhoto'] = imgUserPhoto.join(',')+ ',';
                     } else if(postData.Data.yuang){
                         // 员工码申请
                        console.log('VerifyPhotoUrl--tmpData员工码申请',postData.Data)
                        imgCertPhoto.push(imgUrls[0],imgUrls[1])
                        imgUserPhoto.push(imgUrls[2])
                        tmpData['CertPhoto'] = imgCertPhoto.join(',');
                        tmpData['UserPhoto'] = imgUserPhoto.join(',')+ ',';
                     } else {
                         //ic卡年审
                        console.log('VerifyPhotoUrl--tmpDataic卡年审',postData.Data)
                        imgCertPhoto.push(imgUrls[0],imgUrls[1])
                        imgUserPhoto.push(imgUrls[2]) 
                        tmpData['CertPhoto'] = imgCertPhoto.join(',');
                        tmpData['UserPhoto'] = imgUserPhoto.join(',')+ ',';
                     }
                   
                    // ,imgUrls[3]
               
                }
                if(imgUrls.length==1){
                    imgfirmrPhoto.push(imgUrls[0])
                    tmpData['ConfirmPhoto'] = imgfirmrPhoto.join(',') + ',';
                   
                }
               if (CertNo == undefined) {
                tmpData['AttachPhotoUrl'] = imgUrls.join(',');
               }
            }
               console.log('获取的照片路径tmpData',tmpData)
                    delete tmpData['typefile'];
                    delete tmpData['uidfile'];
                    delete tmpData['CompanyCodefile'];
                    delete tmpData['FilePath']
                    delete tmpData['leix']
                    delete tmpData['yuang']
               console.log('获取的照片路径params',params)

                    if (params.callback)
                        params.callback(tmpData);

                    console.log('成功：' + success + ' 失败：' + fail);
                } else {
                    //若图片还没有传完，则继续调用函数
                    data.i = i;
                    data.success = success;
                    data.fail = fail;
                    uploadImages(data);
                }
            }
        });
    };

    try {
        if (isUploadFile) {

            uploadImages({
                FilePath: data.FilePath
            });
            return;
        }
        let res = await wepy.request({
            url: url,
            // timeout:1000,
            method: params.method || 'post',
            data: JSON.stringify(postData),
            header: header,
        }).catch(res=>{
            let consoleSync = JSON.stringify({page:'wxRequest',Time:util.getDate(null, 'hh:mm:ss'),url:url,errMsg:res.errMsg,Name: '调用接口异常,可能超时!'})+ '\r\n'
            var obja = wx.getStorageSync(ConsoleLog)
           var obja = obja.concat(consoleSync)
            wx.setStorageSync(ConsoleLog, obja)
          })
          let result = res.data;
        console.log('+调用接口--url',url)
        console.log('+调用接口--data',postData.Data)
        console.log('+调用接口--res',res)
          if(result.Code === 0) return result;
          if(result.Code === 999||result.Code === 403) { //小程序登录过期
              let res = await wepy.login();
              if (res.code) {
                  let tmpParams = {
                      data: { JSCode : res.code  }
                    };
                  let lastIndex = url.lastIndexOf('/api/') +5;    
                  let tmpUrl =   url.substr(0,lastIndex) + 'slwx/postlogin';
                let rlt = await wxRequest(tmpParams, tmpUrl);
                let data = rlt.Data
                if (rlt.Code == 0) {
                   wepy.setStorageSync(USER_SPECICAL_INFO,data);
                   return data;
                }
                //重新登录
                wx.redirectTo({
                  url: '/pages/auth'
                });
                return false;
              }
  
          }
          // < 5000  统一提示
          if(result.Code < 5000 && result.Code !== 0) {
              result.Message = '服务正忙，请稍后再试！'
              return result;
           }
           return result;
    } catch (e) {
        console.log(e)
        return { Code: -1001,  Message: '服务正忙，请稍后再试！'};
    } finally {
    }
};


module.exports = {
    wxRequest
}
